import { createRouter, createWebHistory } from "vue-router";
import ChatView from "@/views/ChatView.vue";
import LoginView from "@/views/LoginView.vue";
import RegisterView from "@/views/RegisterView.vue";
import DataLabView from "@/views/DataLabView.vue";
import { loadAuthConfig, getCachedAuthConfig } from "@/services/authService";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      name: "login",
      component: LoginView,
      meta: {
        title: "登录 AI Chat",
        requiresAuth: false,
      },
    },
    {
      path: "/register",
      name: "register",
      component: RegisterView,
      meta: {
        title: "注册 AI Chat",
        requiresAuth: false,
      },
    },
    {
      path: "/chat/:id?",
      name: "chat",
      component: ChatView,
      meta: {
        title: "AI Chat",
        requiresAuth: true,
      },
    },
    {
      path: "/data-lab",
      name: "dataLab",
      component: DataLabView,
      meta: {
        title: "数据实验室",
        requiresAuth: true,
      },
    },
    {
      path: "/",
      beforeEnter: async (to, from, next) => {
        const token = localStorage.getItem("authToken");

        let authConfig = getCachedAuthConfig();
        try {
          authConfig = await loadAuthConfig();
        } catch {
          // fallback to cached/default config
        }

        const authEnabled = authConfig.auth_required;

        if (authEnabled && !token) {
          next("/login");
        } else {
          next("/chat");
        }
      },
    },
    {
      path: "/:pathMatch(.*)*",
      redirect: "/chat",
    },
  ],
});

router.beforeEach(async (to, from, next) => {
  document.title = (to.meta.title as string) || "AI Chat";

  // 简化逻辑：直接检查是否有token
  const token = localStorage.getItem("authToken");
  const isLoginPage = to.path === "/login" || to.path === "/register";

  // 如果没有token且不是登录页面，重定向到登录页面
  if (!token && !isLoginPage) {
    next({ path: "/login", query: { redirect: to.fullPath } });
    return;
  }

  // 如果有token且是登录页面，重定向到聊天页面
  if (token && isLoginPage) {
    next({ path: "/chat" });
    return;
  }

  next();
});

export default router;
